<template>
  <div>
    <van-form @submit="bookTypeOnSubmit" required>
      <van-cell-group inset>
        <van-field
          v-model="taskForm.title"
          input-align="right"
          label="标题"
          placeholder="请输入标题"
          :rules="[{ required: true, message: '请输入标题' }]"
        />
        <van-field
          v-model="taskForm.price"
          input-align="right"
          label="金额"
          placeholder="请输入金额"
          type="number"
          :rules="[{ required: true, message: '请输入金额' }]"
        />
        <van-field
          v-model="taskForm.content"
          label-align="top"
          label="内容"
          placeholder="请输入内容"
          rows="3"
          autosize
          type="textarea"
          maxlength="100"
          show-word-limit
          :rules="[{ required: true, message: '请输入内容' }]"
        />
        <van-field name="uploader" label-align="top">
          <template #input>
            <van-uploader
              preview-size="94px"
              @delete="uploadDelete"
              result-type="file"
              v-model="fileList"
              :max-count="5"
              :after-read="afterRead"
            />
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { addCoinRecord } from "@/service/user";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";
import dayjs from "dayjs";
import { uploadFile } from "../../service/file";

const route = useRoute();
const router = useRouter();

const state = reactive({});

const taskForm = reactive({
  time: dayjs(new Date()).format("YYYY-MM-DD HH:ss"), //	时间
  title: "", //	标题
  content: "", //	内容
  resource: "", //图片或视频资源 json格式
  price: "", //单位 ，显示的显示元 保留两个小数点
});

//图片上传相关
const fileList = ref([]);
const resourceList = ref([]);

//图片上传loading
const afterRead = async (file) => {
  file.status = "uploading";
  file.message = "上传中...";
  const { data, status } = await uploadFile(file.file);
  if (status == 0) {
    file.status = "success";
    file.message = "上传成功";
    file.name = data;
    resourceList.value = resourceList.value.concat({
      url: `${URL}${data}`,
      name: data,
    });
  }
};

//上传 - 删除
const uploadDelete = (file) => {
  resourceList.value = resourceList.value.filter((o) => o.name != file.name);
  showSuccessToast("删除成功");
};

const bookTypeOnSubmit = async () => {
  const { status } = await addCoinRecord({
    ...taskForm,
    ...{
      price: taskForm.price * 100,
      resource: JSON.stringify(resourceList.value),
    },
  });

  if (status == 0) {
    showSuccessToast({
      message: "新增成功",
      onClose: () => {
        router.go(-1);
      },
    });
  }
};
</script>

<style lang="less" scoped></style>
